'use strict';

//读取配置文件，变量config的类型是Object类型
const config = require('./config');
// 用户获取签名的函数
const sign = require('./sign.js');
exports.main = async (event, context) => {
	//event为客户端上传的参数
	let params = event.params || {}
	
	// 生成签名https://tcb-wg7rqciyk5tadjt24e470-6d079d.service.tcloudbase.com/getWXToken
	if (event.action === 'signature') {
		var tokenApiUrl =
			`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.appsecret}`
		// 获取token
		let getToken = await uniCloud.httpclient.request(tokenApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		let token = getToken.data.access_token
		// 获取Ticket
		var ticketApiUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`
		let getTicket = await uniCloud.httpclient.request(ticketApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		let jsapi_ticket = getTicket.data.ticket
		console.log(jsapi_ticket)
		// 获取签名
		let signature=sign(jsapi_ticket, params.url)
		signature.appId=config.appid
		return signature
	}
	//返回数据给客户端
	return event
};

